<?php

require_once("header.php");

if ( $_SESSION['logon'] !== true ) {

	echo 'Login first';

} else {

	$postid = $_POST['postid'];
	$vote = $_POST['vote'];
	// check inputs
	if ( !preg_match("/^[0-9]{1,10}$/i", $postid) ) {
		echo 'Please choose post';
		exit(0);
	}
	if ( !preg_match("/^-?1$/", $vote) ) {
		echo 'Please choose vote';
		exit(0);
	}
	
	// check existing vote
	$exit = $db->query("Select result From vote Where post_id = $postid And user_id = ".$_SESSION['user_id']);
	
	if ( $exit->fetch() ) {
		// update vote
		$update = $db->query("Update vote Set result = $vote Where post_id = $postid And user_id = ".$_SESSION['user_id']);
		
	} else {
		// insert new vote
		$new = $db->query("Insert Into vote(post_id, user_id, vote_time, result) values($postid, ".$_SESSION['user_id'].", '".date('Y-m-d H:i:s')."', $vote)");
		
	}
				
	echo 'OK';

}

?>